import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../services/theme_service.dart';

/// 主题配置面板
class ThemeConfigPanel extends ConsumerStatefulWidget {
  final VoidCallback? onClose;

  const ThemeConfigPanel({Key? key, this.onClose}) : super(key: key);

  @override
  ConsumerState<ThemeConfigPanel> createState() => _ThemeConfigPanelState();
}

class _ThemeConfigPanelState extends ConsumerState<ThemeConfigPanel> {
  // 背景对齐方式选择
  Alignment _selectedAlignment = Alignment.center;

  @override
  void initState() {
    super.initState();
    // 初始化时获取当前的背景对齐方式
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final themeConfig = ref.read(appThemeConfigProvider);
      if (themeConfig.backgroundAlignment != null) {
        setState(() {
          _selectedAlignment = themeConfig.backgroundAlignment!;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final themeConfig = ref.watch(appThemeConfigProvider);
    final themeNotifier = ref.read(appThemeConfigProvider.notifier);
    final isDarkMode = themeConfig.isDarkMode;

    return Container(
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor,
        borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(16),
          topRight: Radius.circular(16),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            spreadRadius: 1,
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 标题栏
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '主题设置',
                  style: Theme.of(
                    context,
                  ).textTheme.titleLarge?.copyWith(fontWeight: FontWeight.bold),
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: widget.onClose,
                ),
              ],
            ),
          ),
          Divider(color: isDarkMode ? Colors.grey.shade700 : null),

          // 主题选择区域
          Expanded(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 预设主题选择
                  Text(
                    '预设主题',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),

                  // 预设主题列表
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      // 粉色渐变主题
                      _buildThemeOption(
                        context,
                        title: '粉色渐变',
                        colors: AppThemeConfig.defaultTheme().gradientColors,
                        isSelected:
                            themeConfig.themeType == AppThemeType.pinkGradient,
                        onTap:
                            () => themeNotifier.setPresetTheme(
                              AppThemeType.pinkGradient,
                            ),
                      ),

                      // 黑夜主题
                      _buildThemeOption(
                        context,
                        title: '黑夜主题',
                        colors: AppThemeConfig.darkTheme().gradientColors,
                        isSelected:
                            themeConfig.themeType == AppThemeType.darkTheme,
                        onTap:
                            () => themeNotifier.setPresetTheme(
                              AppThemeType.darkTheme,
                            ),
                      ),

                      // 灰渐变主题
                      _buildThemeOption(
                        context,
                        title: '灰渐变',
                        colors: AppThemeConfig.greyGradient().gradientColors,
                        isSelected:
                            themeConfig.themeType == AppThemeType.greyGradient,
                        onTap:
                            () => themeNotifier.setPresetTheme(
                              AppThemeType.greyGradient,
                            ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 32),

                  // 自定义主题
                  Text(
                    '自定义主题',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),

                  // 自定义背景图片
                  if (themeConfig.themeType == AppThemeType.custom &&
                      themeConfig.backgroundImagePath != null)
                    _buildCustomThemePreview(context, themeConfig),

                  const SizedBox(height: 16),

                  // 背景图片选择
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8.0),
                    child: Row(
                      children: [
                        Text(
                          '背景图片:',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        const SizedBox(width: 10),
                        ElevatedButton(
                          onPressed: () async {
                            try {
                              final success = await themeNotifier
                                  .pickAndSetBackgroundImage(
                                    opacity: themeConfig.backgroundOpacity,
                                  );

                              if (success && context.mounted) {
                                // 更新背景对齐方式
                                final updatedTheme = ref.read(
                                  appThemeConfigProvider,
                                );
                                if (updatedTheme.backgroundAlignment == null) {
                                  // 如果没有设置对齐方式，使用当前选择的对齐方式
                                  final customTheme =
                                      await AppThemeConfig.fromBackgroundImage(
                                        updatedTheme.backgroundImagePath!,
                                        backgroundOpacity:
                                            updatedTheme.backgroundOpacity,
                                        backgroundAlignment: _selectedAlignment,
                                      );

                                  // 更新状态
                                  themeNotifier.state = customTheme;
                                  await ThemeService().saveThemeConfig(
                                    customTheme,
                                  );
                                }

                                ScaffoldMessenger.of(context).showSnackBar(
                                  const SnackBar(
                                    content: Text('背景图片设置成功，已根据图片提取主题色'),
                                    duration: Duration(seconds: 2),
                                  ),
                                );
                              }
                            } catch (e) {
                              if (context.mounted) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: Text('设置背景图片失败: $e'),
                                    duration: const Duration(seconds: 2),
                                    backgroundColor: Colors.red,
                                  ),
                                );
                              }
                              print('设置背景图片失败: $e');
                            }
                          },
                          style: ElevatedButton.styleFrom(
                            backgroundColor: themeConfig.primaryColor,
                            foregroundColor: Colors.white,
                            padding: const EdgeInsets.symmetric(
                              horizontal: 16,
                              vertical: 12,
                            ),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              const Icon(Icons.image),
                              const SizedBox(width: 8),
                              Text(
                                themeConfig.themeType == AppThemeType.custom
                                    ? '更换背景图片'
                                    : '选择背景图片',
                              ),
                            ],
                          ),
                        ),
                        if (themeConfig.backgroundImagePath != null) ...[
                          const SizedBox(width: 10),
                          IconButton(
                            icon: const Icon(Icons.delete, color: Colors.red),
                            onPressed: () async {
                              // 创建一个没有背景图片的自定义主题
                              final customTheme = themeConfig.copyWith(
                                backgroundImagePath: null,
                                backgroundAlignment: null,
                              );

                              // 更新状态
                              themeNotifier.state = customTheme;
                              await ThemeService().saveThemeConfig(customTheme);
                            },
                            tooltip: '移除背景图片',
                          ),
                        ],
                      ],
                    ),
                  ),

                  // 背景图片对齐方式选择
                  if (themeConfig.backgroundImagePath != null)
                    Padding(
                      padding: const EdgeInsets.symmetric(vertical: 8.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '背景图片位置:',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          const SizedBox(height: 8),
                          Container(
                            height: 150,
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.grey.shade300),
                              borderRadius: BorderRadius.circular(8),
                            ),
                            child: GridView.count(
                              crossAxisCount: 3,
                              padding: const EdgeInsets.all(8),
                              children: [
                                _buildAlignmentButton(Alignment.topLeft, '左上'),
                                _buildAlignmentButton(Alignment.topCenter, '上'),
                                _buildAlignmentButton(Alignment.topRight, '右上'),
                                _buildAlignmentButton(
                                  Alignment.centerLeft,
                                  '左',
                                ),
                                _buildAlignmentButton(Alignment.center, '中'),
                                _buildAlignmentButton(
                                  Alignment.centerRight,
                                  '右',
                                ),
                                _buildAlignmentButton(
                                  Alignment.bottomLeft,
                                  '左下',
                                ),
                                _buildAlignmentButton(
                                  Alignment.bottomCenter,
                                  '下',
                                ),
                                _buildAlignmentButton(
                                  Alignment.bottomRight,
                                  '右下',
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),

                  // 透明度调节（仅当有自定义背景时显示）
                  if (themeConfig.themeType == AppThemeType.custom)
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const SizedBox(height: 24),
                        Text(
                          '背景透明度',
                          style: Theme.of(context).textTheme.titleSmall,
                        ),
                        Row(
                          children: [
                            const Icon(Icons.opacity, size: 16),
                            Expanded(
                              child: Slider(
                                value: themeConfig.backgroundOpacity,
                                min: 0.1,
                                max: 1.0,
                                divisions: 9,
                                label:
                                    '${(themeConfig.backgroundOpacity * 100).round()}%',
                                onChanged: (value) {
                                  themeNotifier.updateBackgroundOpacity(value);
                                },
                              ),
                            ),
                            Text(
                              '${(themeConfig.backgroundOpacity * 100).round()}%',
                            ),
                          ],
                        ),
                      ],
                    ),

                  // 字体设置
                  const SizedBox(height: 24),
                  Text(
                    '字体设置',
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),

                  // 字体选择器
                  Card(
                    elevation: 2,
                    child: Padding(
                      padding: const EdgeInsets.all(12.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '应用字体',
                                style: Theme.of(context).textTheme.titleSmall,
                              ),
                              Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(8.0),
                                  border: Border.all(
                                    color:
                                        isDarkMode
                                            ? Colors.grey.shade700
                                            : Colors.grey.shade300,
                                  ),
                                ),
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 12.0,
                                  vertical: 4.0,
                                ),
                                child: DropdownButton<String>(
                                  value: themeConfig.fontFamily,
                                  underline: const SizedBox.shrink(),
                                  icon: Icon(
                                    Icons.arrow_drop_down,
                                    color: themeConfig.primaryColor,
                                  ),
                                  isDense: true,
                                  borderRadius: BorderRadius.circular(8.0),
                                  items: const [
                                    DropdownMenuItem(
                                      value: 'Cat',
                                      child: Text('猫咪字体'),
                                    ),
                                    DropdownMenuItem(
                                      value: 'Roboto',
                                      child: Text('系统默认'),
                                    ),
                                  ],
                                  onChanged: (value) {
                                    if (value != null) {
                                      themeNotifier.setFontFamily(value);
                                    }
                                  },
                                ),
                              ),
                            ],
                          ),
                          const SizedBox(height: 8),
                          const Text('预览：'),
                          const SizedBox(height: 4),
                          Container(
                            padding: const EdgeInsets.all(8),
                            decoration: BoxDecoration(
                              color:
                                  isDarkMode
                                      ? Colors.grey.shade800
                                      : Colors.grey.shade200,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  '咕噜文件备份',
                                  style: TextStyle(
                                    fontFamily: themeConfig.fontFamily,
                                    fontSize: 18,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '安全、高效、易用的文件备份工具',
                                  style: TextStyle(
                                    fontFamily: themeConfig.fontFamily,
                                    fontSize: 14,
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建主题选项
  Widget _buildThemeOption(
    BuildContext context, {
    required String title,
    required List<Color> colors,
    required bool isSelected,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Column(
        children: [
          Container(
            width: 80,
            height: 80,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: colors,
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              borderRadius: BorderRadius.circular(12),
              border: Border.all(
                color:
                    isSelected
                        ? Theme.of(context).primaryColor
                        : Colors.transparent,
                width: 3,
              ),
              boxShadow: [
                BoxShadow(
                  color: colors[0].withOpacity(0.3),
                  blurRadius: 8,
                  spreadRadius: 1,
                ),
              ],
            ),
            child:
                isSelected
                    ? const Center(
                      child: Icon(
                        Icons.check_circle,
                        color: Colors.white,
                        size: 32,
                      ),
                    )
                    : null,
          ),
          const SizedBox(height: 8),
          Text(
            title,
            style: TextStyle(
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建自定义主题预览
  Widget _buildCustomThemePreview(
    BuildContext context,
    AppThemeConfig themeConfig,
  ) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text('当前背景图片', style: Theme.of(context).textTheme.titleSmall),
        const SizedBox(height: 8),
        Center(
          child: Container(
            width: 200,
            height: 120,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2),
                  blurRadius: 8,
                  spreadRadius: 1,
                ),
              ],
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Stack(
                fit: StackFit.expand,
                children: [
                  // 背景图片
                  Image.file(
                    File(themeConfig.backgroundImagePath!),
                    fit: BoxFit.cover,
                    alignment:
                        themeConfig.backgroundAlignment ?? Alignment.center,
                  ),

                  // 提取的主题色展示
                  Positioned(
                    bottom: 0,
                    left: 0,
                    right: 0,
                    child: Container(
                      padding: const EdgeInsets.symmetric(vertical: 8),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: themeConfig.gradientColors,
                          begin: Alignment.centerLeft,
                          end: Alignment.centerRight,
                        ),
                      ),
                      child: const Center(
                        child: Text(
                          '提取的主题色',
                          style: TextStyle(
                            color: Colors.white,
                            fontWeight: FontWeight.bold,
                            fontSize: 12,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建对齐方式选择按钮
  Widget _buildAlignmentButton(Alignment alignment, String label) {
    final isSelected = _selectedAlignment == alignment;
    final themeConfig = ref.watch(appThemeConfigProvider);
    final primaryColor = themeConfig.primaryColor;

    return GestureDetector(
      onTap: () async {
        setState(() {
          _selectedAlignment = alignment;
        });

        // 只有在有背景图片的情况下才更新对齐方式
        if (themeConfig.backgroundImagePath != null) {
          // 创建更新后的主题配置
          final updatedTheme = themeConfig.copyWith(
            backgroundAlignment: alignment,
          );

          // 更新状态
          ref.read(appThemeConfigProvider.notifier).state = updatedTheme;
          await ThemeService().saveThemeConfig(updatedTheme);
        }
      },
      child: Container(
        margin: const EdgeInsets.all(4),
        decoration: BoxDecoration(
          color:
              isSelected ? primaryColor.withOpacity(0.2) : Colors.transparent,
          border: Border.all(
            color: isSelected ? primaryColor : Colors.grey.shade400,
            width: isSelected ? 2 : 1,
          ),
          borderRadius: BorderRadius.circular(4),
        ),
        child: Center(
          child: Text(
            label,
            style: TextStyle(
              color: isSelected ? primaryColor : null,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      ),
    );
  }
}

/// 显示主题配置面板
void showThemeConfigPanel(BuildContext context) {
  showModalBottomSheet(
    context: context,
    isScrollControlled: true,
    backgroundColor: Colors.transparent,
    builder: (context) {
      return Stack(
        children: [
          // 添加一个透明的遮罩层，点击时关闭面板
          Positioned.fill(
            child: GestureDetector(
              onTap: () => Navigator.pop(context),
              behavior: HitTestBehavior.opaque,
              child: Container(color: Colors.transparent),
            ),
          ),
          // 主题配置面板
          DraggableScrollableSheet(
            initialChildSize: 0.7,
            minChildSize: 0.5,
            maxChildSize: 0.95,
            builder:
                (context, scrollController) =>
                    ThemeConfigPanel(onClose: () => Navigator.pop(context)),
          ),
        ],
      );
    },
  );
}
